package com.ifengchao.service.impl;

import com.ifengchao.dao.iface.DealPlanDao;
import com.ifengchao.service.DealPlanService;
import com.ifengchao.util.zzy.ZhiZiYunUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Deal plan service.
 *
 * @Author YiMing
 * @Description:
 * @Date: Created in 下午7:32 2017/8/31
 * @Modified By
 */
@Service
public class DealPlanServiceImpl implements DealPlanService {

	private static final Logger logger = Logger.getLogger(DealPlanServiceImpl.class);

	@Autowired(required = true)
	private DealPlanDao dealPlanDao;


	@Override
	public void getPlanStatistics() {
		//查询所有智子云广告主id
		List<Map<String, Object>> list = dealPlanDao.queryZzyAdvertiseId();

		//遍历
		for (Map<String, Object> map : list) {
			HashMap<String, Object> hashMap = new HashMap<>();
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH,-1);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String Datetime = sdf.format(now.getTime());
			hashMap.put("starttime", Datetime);
			hashMap.put("endtime", Datetime);
			hashMap.put("advertiserid",map.get("advertiserId"));
			try {
				JSONObject zhiZiYunData = ZhiZiYunUtil.getZhiZiYunData("rtbreport/getByPlan", hashMap);

				if (zhiZiYunData.getBoolean("status")) {
					//获取智子云数据
					JSONObject jsonObject = zhiZiYunData.getJSONObject("response");
					List<JSONObject> data = (List<JSONObject>) jsonObject.get("data");

					//判断data是否有计划
					if (data.size() > 0) {
						//遍历所有计划
						for (JSONObject datum : data) {
							//获取各个计划返回来的数据
							List<Map<String, Object>> reportData = (List<Map<String, Object>>) datum.get("reportData");
							//判断每个计划是否有数据,有就执行插入数据
							if (reportData.size() > 0) {
								Object id = map.get("id");
								Object sar = map.get("sar");
								if (sar == null) {
									sar = 0;
								}
								dealPlanDao.insertZzyStatisticsDay(reportData,id,sar);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("调用智子云接口失败，原因：", e);
			}

		}
	}

	public static void main(String[] args) throws Exception {
		HashMap<String, Object> map = new HashMap<>();
		Calendar now = Calendar.getInstance();
		now.add(Calendar.DAY_OF_MONTH,-1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String Datetime = sdf.format(now.getTime());
		System.out.println(Datetime);
		/*map.put("starttime", "2017-08-01");
		map.put("endtime", "2017-08-29");
		map.put("advertiserid","sf3p90GBxHr");
		JSONObject zhiZiYunData = ZhiZiYunUtil.getZhiZiYunData("rtbreport/getByPlan",map);
		System.out.println(zhiZiYunData);*/

	}
}
